from PySide2.QtWidgets import QApplication, QWidget, QLabel, QVBoxLayout, QHBoxLayout, QPushButton, QTextEdit, QMessageBox
from PySide2.QtCore import Signal
from PySide2.QtGui import QPalette, Qt, QImage, QPixmap
from pathlib import Path

from tool import util, storage, dbutil
from custom.Runthread import OnPlay, OnPlayFFmpeg, OnDownloadAndOther, OnUploadVideo
from custom.ImageWidget import ImageWidget
from custom.VideoWidget import VideoWidget
from model import Video
from manager import Manager
from custom.HVideoWidget import HVideoWidget

DownloadPathKey = "downloadPath"

class VideoItem(QWidget):

    clickedImage = Signal(Video)
    updateUploador_signal = Signal()


    def __init__(self, video):
        super(VideoItem, self).__init__()
        # self.setStyleSheet("background-color:gray;")

        self.video = video
        self.isUpload = True
        self.download_id = 0
        self.upload_id = 0

        path = storage.getValue(DownloadPathKey)
        if not path:
            # 相对路径
            path = str(Path("videos"))
        self.download_path = path

        self.setupUi()
        self.setupData()

    def setupUi(self):
        self.layout = QHBoxLayout(self)
        # self.layout.addStretch(1)

        self.imageLabel = ImageWidget()
        self.imageLabel.setFixedSize(160, 90)
        self.imageLabel.setScaledContents(True)
        self.imageLabel.clicked.connect(self.onClickImage)

        self.imageLayout = QVBoxLayout(self.imageLabel)

        self.creatorLabel = QLabel()
        self.uploadedLabel = QLabel()
        
        self.uploadedLabel.setStyleSheet("color:red")

        self.creatorLayout = QHBoxLayout()
        self.creatorLayout.addWidget(self.creatorLabel)
        self.creatorLayout.addStretch(1)
        self.creatorLayout.addWidget(self.uploadedLabel)
    
        self.centerEmptyLayout = QHBoxLayout()

        self.durationLabel = QLabel()
        self.durationLayout = QHBoxLayout()
        self.durationLayout.addStretch(1)
        self.durationLayout.addWidget(self.durationLabel)

        self.imageLayout.addLayout(self.creatorLayout)
        self.imageLayout.addLayout(self.centerEmptyLayout)
        self.imageLayout.addLayout(self.durationLayout)

        self.imageLayout.setStretchFactor(self.centerEmptyLayout, 1)
        self.imageLayout.setContentsMargins(2, 0, 2, 0)

        self.vlayout = QVBoxLayout()
        self.vlayoutAction = QVBoxLayout()
        self.pushButton = QPushButton("播放")
        self.pushButton.clicked.connect(self.onClickPlay)
        self.uploadButton = QPushButton("上传")
        self.uploadButton.clicked.connect(self.onClickUpload)

        self.downloadButton = QPushButton("下载")
        self.downloadButton.clicked.connect(self.onClickDownload)
        self.vlayoutAction.addWidget(self.pushButton)
        self.vlayoutAction.addWidget(self.uploadButton)
        self.vlayoutAction.addWidget(self.downloadButton)
        self.downloadButton.hide()

        self.layout.addWidget(self.imageLabel)
        self.layout.addLayout(self.vlayout)
        # self.layout.addStretch(1)
        self.layout.addLayout(self.vlayoutAction)

        self.title = QTextEdit()
        self.title.setPlaceholderText("请输入标题")
        self.title.textChanged.connect(self.titleChanged)

        self.vlayout.addWidget(self.title)

        self.tags = QTextEdit()
        self.tags.setPlaceholderText("请输入标签，逗号`,`隔开")
        self.tags.textChanged.connect(self.tagsChanged)
        self.vlayout.addWidget(self.tags)

        self.timeLabel = QLabel("创建时间：")
        self.vlayout.addWidget(self.timeLabel)

    def setupData(self):
        self.pushButton.show()
        self.uploadButton.show()
        self.downloadButton.show()
        self.title.show()
        self.tags.show()
        self.timeLabel.show()
        self.creatorLabel.show()
        self.uploadedLabel.show()
        self.durationLabel.show()

        self.title.setText(self.video.title)
        self.tags.setText(self.video.tags)
        self.timeLabel.setText("创建时间："+str(self.video.create_time))
        
        if self.video.creator_nick != None:
            self.creatorLabel.setText(self.video.creator_nick)
        else:
            self.creatorLabel.setText(self.video.creator_id)
        self.durationLabel.setText(self.video.duration)

        if self.video.is_uploaded:
            self.uploadedLabel.setText("已上传")
        else:
            self.uploadedLabel.setText("")

        if self.pathIsExist():
            self.downloadButton.hide()
        else:
            self.downloadButton.show()

        self.imageLabel.loadImage(self.video.id, self.video.img)


    def reloadData(self, video):
        self.video = video
        self.setupData()

    def clearData(self):
        self.imageLabel.clearImage()

        self.pushButton.hide()
        self.uploadButton.hide()
        self.downloadButton.hide()
        self.title.hide()
        self.tags.hide()
        self.timeLabel.hide()
        self.creatorLabel.hide()
        self.uploadedLabel.hide()
        self.durationLabel.hide()

    def onClickImage(self):
        self.clickedImage.emit(self.video)

    def onClickPlay(self):
        play = self.video.url
        if self.video.real_url != None:
            play = self.video.real_url
        if self.video.path != None:
            play = self.video.path
        
        self.console("【id = {}】准备播放视频".format(self.video.id))
        self.thread = OnPlay(self.video.id, play)
        self.thread.finishsignal.connect(self.onPlayFinish)
        self.thread.start()

    def onPlayFinish(self, urls):
        self.console("【id = {}】播放视频".format(self.video.id))
        self.video.real_url = urls[0]
        
        self.console(urls[0])
        
        self.videoWidget = HVideoWidget()
        self.videoWidget.show()
        self.videoWidget.play(urls[0])

    def onPlayFFmpeg(self, url):
        self.thread = OnPlayFFmpeg(url)
        self.thread.finishsignal.connect(self.onPlayFFmpegFinish)
        self.thread.start()

    def onPlayFFmpegFinish(self):
        self.console("【id = {}】播放完成".format(self.video.id))


    def onClickUpload(self):
        # 比较数量
        if Manager.currentUploador.uploaded_num >= Manager.currentUploador.number:
            QMessageBox.warning(self, '', "最多上传{}个视频".format(
                Manager.currentUploador.number), QMessageBox.Yes)
            return
        if dbutil.isUploadVideo(self.video.id, '1'):
            QMessageBox.warning(self, '', "该平台已经上传了", QMessageBox.Yes)
            return
        if self.video.id == self.upload_id:
            QMessageBox.warning(self, '', "该视频上传中...", QMessageBox.Yes)
            return
        self.upload_id = self.video.id
        self.isUpload = True
        # 1 查看本地是否存在
        if self.pathIsExist():
            # 上传前准备
            self.prepareUpload()
        else:
            # 不存在下载
            self.onDownloadAndOther()


    def titleChanged(self):
        title = self.title.toPlainText()
        if title == self.video.title:
            return
        dic = {'title': title}
        self._updateVideo(dic)
        self.video.title = title

    def tagsChanged(self):
        text = self.tags.toPlainText()
        if text == self.video.tags:
            return
        dic = {'tags': text}
        self._updateVideo(dic)
        self.video.tags = text

    def _updateVideo(self, dic):
        dbutil.updateVideo(self.video.id, dic)

    def onClickDownload(self):
        self.isUpload = False
        self.onDownloadAndOther()

    def onDownloadAndOther(self):
        if self.download_id == self.video.id:
            QMessageBox.warning(self, '', "该视频下载中...", QMessageBox.Yes)
            return
        if self.pathIsExist():
            self.console("【id = {}】已下载".format(self.video.id))
            return

        self.console("【id = {}】请稍后，下载视频中...".format(self.video.id))
        self.download_id = self.video.id
        self.thread = OnDownloadAndOther(
            self.video.url, self.video.vid, self.download_path)
        self.thread.finishsignal.connect(self.onDownloadFinish)
        self.thread.start()

    def onDownloadFinish(self, path):
        # path路径 windows 路径为反斜杠 存不进，不再使用
        self.console("【id = {}】下载视频完成".format(self.video.id))
        self.download_id = 0
        dbutil.updateVideo(self.video.id, {"path": self.video.path})
        self.setupData()
        if self.isUpload:
            self.prepareUpload()

    def prepareUpload(self):
        # TODO 水印 裁剪
        self.thread = OnUploadVideo([self.video])
        self.thread.upload_finish_signal.connect(self.onUploadVideoFinish)
        self.thread.start()

    def onUploadVideoFinish(self):
        self.upload_id = 0
        self.video.is_uploaded = True
        self.setupData()
        self.console("【视频上传成功】")
        self.updateUploador_signal.emit()
        
    def pathIsExist(self):
        if self.video.path == None or len(self.video.path) == 0:
            self.video.path = self.download_path + "/" + self.video.vid + ".mp4"
        if Path(self.video.path).exists():
            return True
        return False

    def console(self, text):
        Manager.consoleWidget.normalOutputWarp(text)
